package com.jishuo.base.service;

import com.github.pagehelper.PageHelper;
import com.jishuo.base.annotation.RoleType;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.bean.vo.RoleVO;
import com.jishuo.base.config.AppConfig;
import com.jishuo.base.dao.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色管理
 */
@Slf4j
@Service
public class RoleService {
    @Resource
    private RoleMapper roleMapper;

    /**
     * 获得制定角色id的菜单权限列表
     * @param roleIds 角色id列表，逗号隔开
     * @return
     */
    public String getMenuIds(String roleIds) {
        roleIds = "," + roleIds + ",";
        String menuIds = "";
        List<RoleVO> list = this.roleMapper.listRole(new RoleVO());
        for (RoleVO role : list) {
            if (roleIds.contains("," + role.getRoleId() + ",")) {
                menuIds += "," + role.getMenuId();
            }
        }
        return menuIds + ",";
    }

    /**
     * 获得权限列表
     * @param role 查询条件
     * @return
     */
    public List<RoleVO> listRole(RoleVO role, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination != null && pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return this.roleMapper.listRole(role);
    }

    /**
     * 根据角色ID获得角色
     * @param roleId 角色ID
     * @return
     */
    public RoleVO getRole(int roleId) {
        return this.roleMapper.getRole(roleId);
    }

    /**
     * 新建角色
     * @param role 角色数据，编号为0时为新增
     * @return
     */
    public BaseResult addRole(RoleVO role) {
        try {
            int ret = this.roleMapper.addRole(role);
            if (ret < 1) return new BaseResult(ErrorCodeEnum.DB_ERR);
            return new BaseResult();
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
    }

    /**
     * 保存角色
     * @param role 角色数据，编号为0时为新增
     * @return
     */
    public BaseResult saveRole(RoleVO role) {
        int ret = this.roleMapper.saveRole(role);
        if (ret < 1) return new BaseResult(ErrorCodeEnum.DB_ERR);
        return new BaseResult();
    }

    /**
     * 删除角色
     * @param roleId 角色id
     * @return
     */
    public BaseResult deleteRole(int roleId) {
        for (RoleType type: RoleType.values()) {
            if (type.getCode() == roleId) return new BaseResult(AppConfig.CUSTOM_ERR, "内置角色，不允许删除");
        }
        return (this.roleMapper.deleteRole(roleId) > 0) ? new BaseResult() : new BaseResult(ErrorCodeEnum.DB_ERR);
    }
}
